package PriorityQueue;

import java.util.Arrays;

public class TestHeap {
    public int [] elem;
    public int usedSize;
    public  TestHeap(){
        this.elem = new int[10];
    }
    public void initElem(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            this.elem[i] = arr[i];
            this.usedSize++;
        }
    }
    public  void creatHeap(){
        for (int parent = (this.usedSize-1-1)/2;parent>=0;parent--){
            siftDown(parent,this.usedSize);
        }
    }

    //这个siftDown是以大堆来进行向下调整

    /**
     *
     * @param parent 每棵子树调整的时候 的起始位置
     * @param usedSize  判断 每棵子树什么时候 调整 结束
     */
    private  void siftDown(int parent,int usedSize){
        int child = 2*parent+1;
        while (child<usedSize){
            if (child+1<usedSize&&elem[child]<elem[child+1]){
                child++;
            }
            if (elem[child]>elem[parent]){
                swap(elem,child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }

    }
    //只是用小堆实现的
    private  void siftDown2(int parent,int usedSize){
        int child = 2*parent+1;
        while (child<usedSize){
            if (child+1<usedSize&&elem[child+1]<elem[child]){
                child++;
            }
            if (elem[child]>elem[parent]){
                swap(elem,child,parent);
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }

    }
    private  void swap(int[] elem,int i,int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] =tmp;
    }
    public  void offer(int val){
        if (isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] =val;
        usedSize++;
    }
    private  void siftUp(int child){
        int parent = (child-1)/2;
        while (parent>=0){
            if (elem[child]>elem[parent]){
                swap(elem,child,parent);
                child =parent;
                parent = (child-1)/2;
            }
        }
    }
    public  boolean isFull(){
        return usedSize==elem.length;
    }
    public  int poll(){
        if (isEmpty()){
            return -1;
        }
        int val = elem[0];
        swap(elem,0,usedSize-1);
        siftDown(0,usedSize-1);
        usedSize--;
        return val;
    }

    public int peek(){
        if (isEmpty()){
            return  0;
        }
        return  elem[0];
    }
    public  boolean isEmpty(){
        return usedSize==0;
    }
    public  void heapSort(){
        int end = usedSize-1;
        while (end >0){
            swap(elem,0,end);
            siftDown(0,end);
            end--;
        }
    }
}
